
import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = () => {
  return {
    // 刷新页面的时候，从本地取token，借助逻辑或短路
    token: getToken() || '',
    // 存储用户信息
    userInfo: {}
  }
}
const mutations = {
  // 设置token
  setToken: (state, token) => {
    state.token = token
    // 本地再存一份token
    setToken(token)
  },
  // 设置用户信息
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // 退出登录清空token和userInfo
  removeToken: (state) => {
    state.token = ''
    // 清空本地token
    removeToken()
  },
  removeUserInfo: (state) => {
    state.userInfo = {}
  }

}
const actions = {
  // 登录action
  loginAction: async({ commit }, loginForm) => {
    // 发登录请求
    const resp = await loginAPI(loginForm)
    // 提交mutation
    commit('setToken', resp.data)
  },
  // 获取用户信息
  getUserInfoAction: async({ commit }) => {
    // 调接口发请求(结构+重命名)
    const { data: userProfile } = await getUserProfileAPI()
    // 基于此次接口返回的用户id继续发起第二次请求（获取头像等信息）
    const { data: userInfo } = await getUserInfoAPI(userProfile.userId)
    // 提交mutation
    commit('setUserInfo', { ...userProfile, ...userInfo })
  },
  // 退出登录
  logoutAction: ({ commit }) => {
    commit('removeToken')
    commit('removeUserInfo')
    // 重置路由实例
    resetRouter()
    // 清空vuex中路由
    commit('route/removeRoutes', null, {
      // 从全局出发
      root: true })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions

}
